<template>
  <div class="container">
    <h1 class="title">Port To Lucky</h1>
    
    <div class="card proxy-status" :class="{ 'running': isRunning }">
      <h2 class="card-title1">
        <span class="status-icon" :class="{ 'warning': !isRunning }"></span>
        代理状态: {{ isRunning ? '运行中' : '已停止' }}
      </h2>
      <div v-if="isRunning" class="proxy-list">
        <div v-for="(proxy, index) in proxyList" :key="index" class="proxy-item">
          <div class="proxy-info">
            <span class="proxy-name">{{ proxy.ruleName }}</span>
            <span class="proxy-port">端口: {{ proxy.localport }}</span>
          </div>
          <div class="button-container">
          <div @click="openProxy(proxy.localport)" class="open-link">
            <img src="./assets/images/web.svg" alt="Open" class="button-icon"/>
          </div>
          <div @click="copyToClipboard(`127.0.0.1:${proxy.localport}`)" class="copy-link">
            <img src="./assets/images/copy.svg" alt="Open" class="button-icon"/>
          </div>
          <div></div>
          <div class="proxy-indicator"></div>
          </div>
          
        </div>
      </div>
      <p v-else class="no-proxy">当前没有运行中的代理</p>
    </div>

    <div class="actions">
      <button 
        @click="toggleConfig" 
        class="macos-button secondary"
      >
        {{ showConfig ? '隐藏配置' : '显示配置' }}
      </button>
      <button 
        @click="toggleProxy" 
        :disabled="loading || !configLoaded"
        :class="['macos-button', isRunning ? 'stop' : 'start']"
      >
        {{ loading ? '处理中...' : (isRunning ? '停止代理' : '启动代理') }}
      </button>
    </div>

    <transition name="fade">
      <div v-if="showConfig" class="card config-section">
        <h2 class="card-title">当前配置   <button @click="editConfig" class="edit-config-button macos-button secondary">编辑</button></h2>
       
        <div class="config-content">
          <div class="config-item">
            <strong>API 地址：</strong> {{ config.API_URL }}
          </div>
          <!-- <div class="config-item">
            <strong>GOST 路径：</strong> 
            {{ isWindows ? config.gost_path_windows : config.gost_path_unix }}
          </div> -->
        </div>
        
        <div class="rules-section">
          <h3 class="subtitle">代理规则：</h3>
          <div v-for="(rule, index) in config.ruleInfo" :key="index" class="rule-card">
            <div><strong>规则名称：</strong> {{ rule.ruleName }}</div>
            <div><strong>Home 地址：</strong> {{ rule.homeAddr }}</div>
            <div><strong>本地端口：</strong> {{ rule.localport }}</div>
            <div><strong>网络协议:</strong> {{ rule.network }}</div>
          </div>
        </div>
      </div>
    </transition>

    <div v-if="status" :class="['status-alert', { 'error': status.includes('失败') || status.includes('错误') }]">
      <span class="status-icon" :class="{ 'error': status.includes('失败') || status.includes('错误')|| status.includes('停止')|| status.includes('stopped')  }"></span>
      {{ status }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const status = ref('')
const loading = ref(false)
const configLoaded = ref(false)
const isRunning = ref(false)
const proxyList = ref([])
const showConfig = ref(false)
const config = ref({
  API_URL: '',
  gost_path_windows: '',
  gost_path_unix: '',
  ruleInfo: []
})
const isWindows = navigator.platform.includes('Win')

const editConfig=()=>{

   window.go.main.App.EditConfig()

  }
const openProxy=(port)  =>{
  const portStr = String(port); 
   window.go.main.App.OpenURLInDefaultBrowser(portStr)
  }
  
  const copyToClipboard=(text)=> {
    try {
      // 使用 navigator.clipboard.writeText 将文本复制到剪贴板
       navigator.clipboard.writeText(text);
      // 可选：显示成功消息给用户
      // window.go.main.App.AlertMsgbox("已复制文本："+text) //系统框不好看
      showToast("已复制文本："+text)
    } catch (err) {
      console.error('Failed to copy text: ', err);
      // 可选：显示错误消息给用户
      alert("复制失败，请尝试手动复制。");
    }
  }

/**
 * 
 * @param message 自定义消息框
 */
  function showToast(message) {
    const toast = document.createElement('div')
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 10px 20px;
        border-radius: 4px;
        z-index: 9999;
    `
    toast.textContent = message
    document.body.appendChild(toast)
    
    setTimeout(() => {
        document.body.removeChild(toast)
    }, 2000)
}

const loadConfig = async () => {
  try {
    loading.value = true
    status.value = '正在加载配置...'
    const loadedConfig = await window.go.main.App.LoadConfig()
    config.value = loadedConfig
    configLoaded.value = true
    status.value = '配置加载成功'
    await updateProxyStatus()
  } catch (error) {
    status.value = `配置加载失败: ${error.message}`
    configLoaded.value = false
  } finally {
    loading.value = false
  }
}

const updateProxyStatus = async () => {
  try {
    const proxyStatus = await window.go.main.App.GetProxyStatus()
    if (typeof proxyStatus === 'object' && proxyStatus !== null) {
      isRunning.value = proxyStatus.isRunning || false
      proxyList.value = proxyStatus.proxyList || []
    } else if (Array.isArray(proxyStatus)) {
      const [running, list] = proxyStatus
      isRunning.value = running || false
      proxyList.value = Array.isArray(list) ? list : []
    }
  } catch (error) {
    // console.error('获取代理状态失败:', error)
    status.value = '获取代理状态失败'
  }
}

const toggleProxy = async () => {
  if (!configLoaded.value) {
    status.value = '请先加载配置'
    return
  }
  
  try {
    loading.value = true
    if (isRunning.value) {
      const result = await window.go.main.App.StopProxy()
      status.value = result || '代理已停止'
    } else {
      const result = await window.go.main.App.StartProxy()
    
      status.value = result || '代理已启动'
    }
    await updateProxyStatus()
  } catch (error) {
    // console.log(error)
    status.value = `错误: ${error}`
  } finally {
    loading.value = false
  }
}

const toggleConfig = () => {
  showConfig.value = !showConfig.value
}

onMounted(async () => {
  await loadConfig()
})
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 100%;
  min-height: 100vh; /* 保证最小高度为视窗高度 */
  margin: 0 auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
  background-color: #1e1e1e;
  color: #e0e0e0;
}

.title {
  font-size: 28px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #ffffff;
}

.card {
  background-color: #2c2c2c;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}
.card-title1 {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #ffffff;
  display: flex;
  align-items: center;
}

.card-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 15px;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between; /* 新增：使子元素左右分开 */
}
.edit-config-button {
  margin-left: auto; /* 新增：将按钮推到最右侧 */
}
.config-content, .rules-section {
  margin-top: 15px;
}

.config-item {
  margin-bottom: 10px;
}

.rule-card {
  background-color: #3a3a3a;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
}

.proxy-status {
  background-color: #2c2c2c;
  transition: background-color 0.3s ease;
}

.proxy-status.running {
  background-color:rgb(64, 71, 77);
}

.proxy-list {
  display: grid;
  gap: 10px;
}

.proxy-item {
  background-color: #3a3a3a;
  border-radius: 8px;
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 使按钮容器中的按钮水平排列 */
.button-container {
  display: flex;
  gap: 10px; /* 按钮之间的间距 */
}

/* 可选：为按钮添加一些样式 */
.open-link, .copy-link {
  cursor: pointer;
  /* padding: 4px 8px;
  background-color: #007bff;
  color: white;
  border-radius: 4px;
  transition: background-color 0.3s; */
}

/* .open-link:hover, .copy-link:hover {
  background-color: #0056b3;
} */

.proxy-info {
  display: flex;
  flex-direction: column;
}

.proxy-name {
  font-weight: 500;
  color: #ffffff;
}

.proxy-port {
  font-size: 14px;
  color: #b0b0b0;
}

.proxy-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #4caf50;
}

.no-proxy {
  color: #b0b0b0;
  font-style: italic;
}

.actions {
  display: flex;
  gap: 10px;
  margin: 20px 0;
}

.macos-button {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  background-color:rgb(5, 147, 38);
  color: white;
}

.macos-button:hover {
  background-color:rgb(5, 138, 36);
}

.macos-button:active {
  background-color: #003399;
}

.macos-button:disabled {
  background-color: #444444;
  cursor: not-allowed;
}

.macos-button.secondary {
  background-color: #3a3a3a;
}

.macos-button.secondary:hover {
  background-color: #4a4a4a;
}

.macos-button.stop {
  background-color: #ff453a;
}

.macos-button.stop:hover {
  background-color: #cc3a2f;
}

.status-alert {
  padding: 15px;
  margin-top: 20px;
  border-radius: 8px;
  background-color:rgb(66, 75, 82);
  border: 1px solid #2c5a2c;
  display: flex;
  align-items: center;
}

.status-alert.error {
  background-color: #4a1c1c;
  border: 1px solid #5a2c2c;
}

.button-icon {
  width: 24px; /* 根据实际图标大小调整 */
  height: 24px;
}

.status-icon {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 10px;
  background-color: #4caf50;
}

.status-icon.error {
  background-color: #f44336;
}
.status-icon.warning {
  background-color: #d19b07;
}

.status-icon.running {
  background-color: #4caf50;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>